<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="type">
        <el-input v-model="queryParams.taskName" placeholder="请输入" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="国家" prop="country">
        <el-select clearable v-model="queryParams.country" style="width: 240px">
          <el-option v-for="item in countryList" :key="item" :value="item">{{ item }}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="margin-left: 22px;">
        <el-date-picker v-model="dateRange" value-format='yyyy-MM-dd HH:mm:ss' type="datetimerange" :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button class="cF" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button class="cF" type="primary" icon="el-icon-plus" size="mini" @click="handleAddShow">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload class="cF" action="/api/number/upload" name="file" :before-upload="handleBeforeUpload" :on-error="handleUploadError" :on-success="handleUploadSuccess">
          <el-button size="mini" type="primary" icon="el-icon-upload">上传国家移动号码段</el-button>
        </el-upload>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="任务名称" align="center" prop="taskName" min-width="10%" />
      <el-table-column label="国家" align="center" prop="country" min-width="10%" />
      <el-table-column label="总数量" align="center" prop="totalNum" min-width="10%" />
      <el-table-column label="有效数" align="center" prop="successNum" min-width="10%">
        <template slot-scope="scope">
          <span>{{ scope.row.successNum }}</span>
          <el-button size="mini" @click="refreshSuccessNums(scope.row)" style="margin-left: 10px;background-color: #9dd982;">查看实时筛选数量</el-button>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="20%" />
      <el-table-column label="状态" align="center" prop="status" min-width="10%">
        <template slot-scope="scope">
          <dict-tag :options="statusDict" :value="scope.row.status" :class="getStatusClass(scope.row.status)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="20%">
        <template slot-scope="scope">
          <el-button size="mini" icon="el-icon-download" @click="downloadFiles(scope.row, 0)" style="background-color: #9dd982; color: black; font-weight: bold;">下载生成手机号</el-button>
          <el-button v-if="[3, 4].includes(scope.row.status)" size="mini" icon="el-icon-download" style="background-color: #9dd982; color: black; font-weight: bold;" @click="downloadFiles(scope.row, 1)">下载筛选手机号</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.per_page" @pagination="getList" />

    <el-dialog title="新增" :visible.sync="addDialogOpen" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="任务名称:" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="国家:" prop="country">
          <el-row>
            <el-col :span="1.5">
              <el-select clearable v-model="form.country">
                <el-option v-for="item in countryList" :key="item" :value="item">{{ item }}</el-option>
              </el-select>
            </el-col>
            <el-col :span="1.5" style="margin-left: 10px;">
              <el-upload class="cF" action="/api/number/upload" name="file" :before-upload="handleBeforeUpload" :on-error="handleUploadError" :on-success="handleUploadSuccess">
                <el-button size="mini" type="primary" icon="el-icon-upload">上传国家移动号码段</el-button>
              </el-upload>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="目标来源:" prop="type">
          <el-radio v-model="form.type" label="1">在线生成</el-radio>
        </el-form-item>
        <el-form-item label="执行时间:" prop="executeTime">
          <el-date-picker v-model="form.executeTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否筛选手机号:" prop="step">
          <el-radio v-model="form.step" label="1">是</el-radio>
          <el-radio v-model="form.step" label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="生成号码数量:" prop="totalNum">
          <el-input-number v-model="form.totalNum" :min="1" :max="999999"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleAddHide">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getCountryList, getWhatsAppList, getWhatsAppDownload, whatsAppAddOrUpdateTask, countFileLine } from "@/api/monitor/job";
export default {
  components: {
  },
  name: "visitorList",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表单参数
      form: {
        type: '1',
        step: '1'
      },
      rules: {
        taskName: [
          { required: true, message: "必填", trigger: "blur" }
        ],
        country: [
          { required: true, message: "必填", trigger: "blur" }
        ],
        executeTime: [
          { required: true, message: "必填", trigger: "blur" }
        ],
        totalNum: [
          { required: true, message: "必填", trigger: "blur" }
        ]
      },
      // 日期范围
      dateRange: [],
      // 遮罩层
      loading: false,
      // 查询参数
      queryParams: {
        page: 1,
        per_page: 10,
        task_name: undefined,
        country: undefined,
        start_time: undefined,
        end_time: undefined
      },
      dataList: [],
      countryList: [],
      uploadFile: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      addDialogOpen: false,
      statusDict: [{
        label: '任务待执行',
        value: '0',
        raw: {
          listClass: 'primary'
        }
      }, {
        label: '号码生成中',
        value: '1',
        raw: {
          listClass: 'warning'
        }
      }, {
        label: '号码生成完成',
        value: '2',
        raw: {
          listClass: 'success'
        }
      }, {
        label: '号码筛选中',
        value: '3',
        raw: {
          listClass: 'warning'
        }
      }, {
        label: '号码筛选完成',
        value: '4',
        raw: {
          listClass: 'success'
        }
      }]
    };
  },
  created() {
    this.getCountry()
    this.getList();
  },
  methods: {
    getStatusClass(status) {
      const statusClassMap = {
        '0': 'status-0',
        '1': 'status-1',
        '2': 'status-2',
        '3': 'status-3',
        '4': 'status-4'
      };
      return statusClassMap[status] || '';
    },
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    getCountry() {
      getCountryList().then((response) => {
        this.countryList = response.countryList || []
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getList() {
      //   this.loading = true;
      getWhatsAppList(
        this.addDateRange2(this.queryParams, this.dateRange)
      ).then((response) => {
        this.dataList = response.taskList;
        this.total = response.total;
        //   this.loading = false;
      });
    },
    handleAddShow() {
      this.addDialogOpen = true
    },
    handleAddHide() {
      this.addDialogOpen = false
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          whatsAppAddOrUpdateTask({ ...this.form }).then((response) => {
            this.$modal.msgSuccess("操作成功");
            this.handleAddHide()
            this.getList()
          })
        }
      });
    },
    downloadFiles(row, flag) {
      let absolute_path = flag == 1 ? row.numberSPath : row.numberGPath
      getWhatsAppDownload({ absolute_path }).then((response) => {
        console.log(response)
      })
    },
    handleBeforeUpload(file) {
      this.$modal.loading("正在上传文件，请稍候...");
      return true;
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      if (res && !!Object.keys(res).length) {
        this.uploadFile = res;
        this.getCountry()
        this.$modal.msgSuccess("上传成功");
        this.$modal.closeLoading();
      }
    },
    handleUploadError(err) {
      this.$modal.msgError("上传失败，请重试");
      this.$modal.closeLoading();
    },
    refreshSuccessNums(row) {
      countFileLine({ task_id: row.id, file_path: row.numberSPath }).then((response) => {
        if (response.error) {
          // 如果存在error字段，显示错误信息
          this.$modal.msgError(response.error);
        } else {
          // 不存在error字段，显示成功信息
          this.$modal.msgSuccess(`有效数：<strong style="font-size: 16px">${response.count}</strong>`, {
            dangerouslyUseHTMLString: true
          });
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.table-row {
  text-align: left;
}

.status-0 {
  font-weight: bold;
}

.status-1 {
  font-weight: bold;
}

.status-2 {
  font-weight: bold;
}

.status-3 {
  font-weight: bold;
}

.status-4 {
  font-weight: bold;
}
</style>
